#include "geocoder.h"

string requestType = "http://maps.google.com/maps/geo?q=";
string mapsAPIKey = "ABQIAAAArHr2R681bOacRTA7NiR7KRTIKY0J4v1euTkM_44KO8g9LlpXpRQNl7-CwQWCn5E2wBhD4HlBksrcwg";
string requestKeys = "&output=json&oe=utf8&oe=utf8&sensor=false&hl=ru&gl=ru&key=" + mapsAPIKey;	

Geocoder::Geocoder() : city_("") { }

void Geocoder::GetCoordinates(vector<Place>& places){
	Network network;
	
	for(std::vector<Place>::iterator i = places.begin(); i != places.end(); ++i){
		string name = (*i).getName();
		
		replace(name.begin(), name.end(), ' ', '+');

		string request = requestType + city_ + ",+" + name + requestKeys;
		string response = network.sendGET(request);
		
		//checking status
		//example:    "code": 200,
		if (response.find("\"code\": 200,") == -1 ){
			continue;  //nothing found on google maps. Maybe delete from places list ?
		}

		//getting adress
		//example:   "address": "Невский просп., 30, город Санкт-Петербург, Россия, 191011",
		string addressBeginTag = "address\": \"";
		int addressBeginPos = response.find(addressBeginTag);
		if(addressBeginPos == -1) continue;
		addressBeginPos += addressBeginTag.length();
		int addressEndPos = response.find("\n", addressBeginPos) - 2;
		string address = response.substr(addressBeginPos, addressEndPos - addressBeginPos);

		//getting coordinates
		//example:      "coordinates": [ 30.3270367, 59.9356409, 0 ]
		string coordinatesBeginTag = "\"coordinates\": [ ";
		int lonBeginPos = response.find(coordinatesBeginTag) + coordinatesBeginTag.length();
		int lonEndPos = response.find(",", lonBeginPos);
		char* pEnd;
		double lon = strtod(response.substr(lonBeginPos, lonEndPos - lonBeginPos).c_str(), &pEnd);

		int latBeginPos = lonEndPos + 2;
		int latEndPos = response.find(",", latBeginPos);
		double lat = strtod(response.substr(latBeginPos, latEndPos - latBeginPos).c_str(), &pEnd);
		
		//setting new options
		(*i).setAddress(address);
		(*i).setCoordinates(lat, lon);
	}//for
}

string Geocoder::SendRequest(string placeName){
	Network network;
	replace(placeName.begin(), placeName.end(), ' ', '+');
	string request = requestType + city_ + ",+" + placeName + requestKeys;
	string response = network.sendGET(request);
	return response;
}

void Geocoder::setCityName(string city){
	city_ = city;
}







